<?php

extract(extractPost(), EXTR_PREFIX_ALL, 'c');

if(isset($c_id) && isset($c_reason) && isset($c_user_id)){

    $card = R::load('card', $c_id); if($card->id==0) jsonErrorDie("Card not exists");
    $project_id = $card->project_id;
    $project = R::load('project', $project_id); if($project->id==0) jsonErrorDie("Project does not exists");
   
    $devGroup = R::load('group', $project->dev_group); if($devGroup->id==0) jsonErrorDie("Group does not exists");
    
//    echo $devGroup->name;
    $kanbanMaster = false;
    $productOwner = false;
    $delete = false;
 
    if($devGroup->kanban_master == $c_user_id){
//        echo "kanban true";
        $kanbanMaster = true;
        $delete = true;
    } 
    if($devGroup->product_owner == $c_user_id){
//        echo "product owner true";
        $productOwner = true;
    }
    
    // 0 - Product Owner
    // Product Owner lahko briše kartico, dokler se ne prične razvoj.

    if($productOwner == true){
    
        $board_id = $card->board_id;
        $leviStolpecRazvoja_id =  R::getCell( "SELECT * FROM `column` WHERE boundary = -1 AND board_id = ?", array($board_id));
        $desniStolpecRazvoja_id = R::getCell( "SELECT * FROM `column` WHERE boundary = 1 AND board_id = ?", array($board_id));

//        echo "levi stolpec razvoja: " . $leviStolpecRazvoja_id;
//        echo "desni stolpec razvoja: " . $desniStolpecRazvoja_id;
        
        $desniStolpecRazvoja = R::load('column', $desniStolpecRazvoja_id);
        $leviStolpecRazvoja = R::load('column', $leviStolpecRazvoja_id);

//        echo "levi stolpec razvoja: " . $leviStolpecRazvoja->position . "\n"; 
//        echo "desni stolpec razvoja: " . $desniStolpecRazvoja->position. "\n";
//        echo "card position: " . $card->position. "\n";
        
        $trenutniStolpecKartice = R::load('column', $card->column_id);
        
//        echo "board_id: " . $board_id;
        // Dobimo vse stolpce, ki so med -1 in 1
        $columns = R::getAll("SELECT * FROM `column` WHERE position >= :leftColumn AND position <= :rightColumn AND board_id = :board_id", ["leftColumn" => $leviStolpecRazvoja->position, ":rightColumn" => $desniStolpecRazvoja->position, ":board_id" => $board_id]);
//        $cards = R::getAll("SELECT * FROM `card` WHERE board_id = ?", array($board_id));

        if($trenutniStolpecKartice->position < $leviStolpecRazvoja->position){
            $delete = true;
        } else {
            jsonErrorDie("Razvoj se je ze pricel!");
        }
    }
    if($delete){
        if($card->active == 1){
            $card->active = 0;
            $card->reason = $c_reason;
            $c_id = R::store( $card );
            jsonSuccessDie("Card is now inactive: " . $c_reason , $c_id);
        } else {
            jsonErrorDie("Card is already inactive."); 
        }
    } else {
        jsonErrorDie("You don't have permissions to delete cards.");
    }
    
}

